package com.ukao.cashregister.dialog;

import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ukao.cashregister.R;
import com.ukao.cashregister.base.BaseDialogFragment;
import com.ukao.cashregister.bean.QueryPaBean;
import com.ukao.cashregister.bean.QuiryDetailBean;
import com.ukao.cashregister.bean.RefundMethodBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.listener.MyTextWatcher;
import com.ukao.cashregister.listener.OnDialogSureClickListener;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DecimalUtil;
import com.ukao.cashregister.utils.DensityUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.SpanUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.StateImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.ukao.cashregister.R.id.view;


/**
 * 退洗
 * Created by ukaodev on 2017/6/2.
 */

public class RefundPayDialogFragment extends BaseDialogFragment {

    Unbinder unbinder;
    @BindView(R.id.close_btn)
    StateImageView closeBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.select_clothing_hite)
    TextView selectClothingHite;
    @BindView(R.id.orderNo)
    TextView orderNo;
    @BindView(R.id.payMethodText)
    TextView payMethodText;
    @BindView(R.id.paidPrice)
    TextView paidPrice;
    @BindView(R.id.payMethodText1)
    TextView payMethodText1;
    @BindView(R.id.backe_paidPrice)
    TextView backePaidPrice;
    @BindView(R.id.import_pice_hite)
    TextView importPiceHite;
    @BindView(R.id.import_pice)
    EditText importPice;
    @BindView(R.id.can_back_pice)
    TextView canBackPice;
    @BindView(R.id.refundBalance_text)
    TextView refundBalanceText;
    @BindView(R.id.refundupay_text)
    TextView refundupayText;
    @BindView(R.id.refundthor_text)
    TextView refundthorText;
    @BindView(R.id.radiogroup)
    RadioGroup radiogroup;
    @BindView(R.id.name_phone)
    TextView namePhone;
    @BindView(R.id.statusText)
    TextView statusText;
    @BindView(R.id.backe_paid_cause)
    TextView backePaidCause;
    @BindView(R.id.backe_cause)
    EditText backeCause;
    @BindView(R.id.cancel)
    StateButton cancel;
    @BindView(R.id.submit)
    Button submit;


    private QuiryDetailBean mQuiryDetailBean;
    private String strPaidPrice;
    private boolean isOrderRefund;
    private String refundablePrice;
    private ArrayList<QueryPaBean> mQuerypayData;
    private ArrayList<RefundMethodBean> mRefundMethodBean;
    private List<Integer> ids = new ArrayList<>();
    boolean isBalance;
    boolean isUpay;
    private double refundBalance;
    private double refundUpay;
    private int payRatio;
    private   View  view;
    /**
     * @param mQuiryDetailBean  订单信息
     * @param mQuerypayData     支付方式
     * @param isOrderRefund     是否是订单退款
     * @param mRefundMethodBean 退款选择方式
     * @return
     */
    public static RefundPayDialogFragment newInstance(QuiryDetailBean mQuiryDetailBean, ArrayList<QueryPaBean> mQuerypayData, ArrayList<RefundMethodBean> mRefundMethodBean, boolean isOrderRefund) {
        RefundPayDialogFragment fragment = new RefundPayDialogFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, mQuiryDetailBean);
        args.putSerializable(ARG_PARAM2, mQuerypayData);
        args.putSerializable(ARG_PARAM3, mRefundMethodBean);
        args.putBoolean(ARG_PARAM4, isOrderRefund);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mQuiryDetailBean = (QuiryDetailBean) getArguments().getSerializable(ARG_PARAM1);
            mQuerypayData = (ArrayList<QueryPaBean>) getArguments().getSerializable(ARG_PARAM2);
            mRefundMethodBean = (ArrayList<RefundMethodBean>) getArguments().getSerializable(ARG_PARAM3);
            isOrderRefund = getArguments().getBoolean(ARG_PARAM4, false);
        }

    }

    private OnDialogSureClickListener mOnDialogSureClickListener;

    public void setOnSureClickListener(OnDialogSureClickListener mOnDialogSureClickListener) {
        this.mOnDialogSureClickListener = mOnDialogSureClickListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         view = inflater.inflate(R.layout.dialog_refund_pay_layout, container, false);
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getDialog().setCanceledOnTouchOutside(false);

        fillData();
        initListener();
    }

    @Override
    protected void initListener() {
        super.initListener();
        importPice.addTextChangedListener(mTextWatcher);


    }

    private void initRaidoGroup() {

        if (!CheckUtils.isEmpty(mRefundMethodBean))
            for (int i = 0; i < mRefundMethodBean.size(); i++) {
                RadioButton rb = (RadioButton) LayoutInflater.from(activity).inflate(R.layout.order_radiogroup_item, null);
                RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                rb.setId(i);
                rb.setText(mRefundMethodBean.get(i).getText());
                lp.setMargins(DensityUtils.dip2px(activity, 15), 0, 0, 0);
                radiogroup.addView(rb, lp);

            }



    }


    TextWatcher mTextWatcher = new MyTextWatcher() {


        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            String count = s.toString().trim();
            Constant.calculate(count, importPice);
            if (!count.isEmpty() && mQuiryDetailBean.getPayStatus()) {
                try {
                    double douPice = Double.parseDouble(count);
                    double douPaidPric = Double.parseDouble(refundablePrice);
                    double refundPice = 0;
                       /*余额*/
                    if (isBalance && refundBalance != 0) {
                        if (douPice > refundBalance) {  /*退全部余额*/
                            refundPice = refundBalance;
                            refundBalanceText.setText(mustSpanText(DecimalUtil.multiplCurrent(refundBalance + ""), "  退至余额", R.color.txt_gray));
                        } else {
                            refundPice = douPice;
                            refundBalanceText.setText(mustSpanText(DecimalUtil.multiplCurrent(douPice + ""), "  退至余额", R.color.txt_gray));
                        }


                    }
                        /*优付卡*/
                    if (isUpay && refundUpay != 0&&payRatio!=0) {
                        if (douPice<=douPaidPric){  /*退当前的输入的金额*/
                            refundPice = calculateUpayPice(douPice);

                        }else{/*退可输入的金额*/
                            refundPice = calculateUpayPice(douPaidPric);
                        }



                    }

                        /*小于或者等于可退金额*/
                    if (douPice <= douPaidPric) {

                        if (douPice > refundPice) {
                            radiogroup.setVisibility(View.VISIBLE);
                            refundthorText.setText(mustSpanText(DecimalUtil.subtract(String.valueOf(douPice),String.valueOf(refundPice)) + "", "元退至", R.color.txt_gray));
                        }else  {
                            refundthorText.setText("");
                            radiogroup.setVisibility(View.INVISIBLE);
                        }

                    } else if (douPaidPric > refundPice) {
                        radiogroup.setVisibility(View.VISIBLE);
                        refundthorText.setText(mustSpanText(DecimalUtil.subtract(String.valueOf(douPaidPric) ,String.valueOf(refundPice)) + "", "元退至", R.color.txt_gray));

                    } else {
                        radiogroup.setVisibility(View.INVISIBLE);

                        refundthorText.setText("");
                    }


                    canBackPice.setVisibility(douPice > douPaidPric ? View.VISIBLE : View.GONE);
                    submit.setEnabled(douPice > douPaidPric ? false : true);
                } catch (Exception e) {
                    canBackPice.setVisibility(View.GONE);
                    submit.setEnabled(true);
                }


            } else {


                radiogroup.setVisibility(View.INVISIBLE);
                refundthorText.setText("");
                refundBalanceText.setText("");
                refundupayText.setText("");
            }
        }
    };

    public double calculateUpayPice(double douPice) {
        double refundPice;
        String  strRefundAmount= DecimalUtil.multiply(String.valueOf(douPice), CheckUtils.isEmptyNumber(payRatio));
        double refundAmount =Double.parseDouble(strRefundAmount );/*得到可退金额*/
        if (refundUpay >= refundAmount) {  /*退全部优付卡*/
            refundPice =refundAmount;
            refundupayText.setText(mustSpanText(strRefundAmount, "  (支付比例" + payRatio + "%)退至优付卡", R.color.txt_gray));
        } else {
            refundPice = refundUpay;
            refundupayText.setText(mustSpanText(DecimalUtil.multiply(refundUpay+""), "  (支付比例" + payRatio + "%)退至优付卡", R.color.txt_gray));
        }
        return refundPice;
    }


    private void fillData() {
        initRaidoGroup();
        title.setText("衣物退洗");
        orderNo.setText("订单号：" + mQuiryDetailBean.getOrderNo());
        namePhone.setText("客户：" + mQuiryDetailBean.getUserInfo().getName() + "  " + mQuiryDetailBean.getUserInfo().getPhone());
        List<QuiryDetailBean.ProductListBean> mproductList = mQuiryDetailBean.getProductList();
        calculateClotingCount(mproductList);
        if (mQuiryDetailBean.getPayStatus()) {
            strPaidPrice = CheckUtils.isEmptyNumber(mQuiryDetailBean.getPaidPrice());
            refundablePrice = CheckUtils.isEmptyNumber(mQuiryDetailBean.getRefundablePrice());/*可退款金额*/
            paidPrice.setText("实付金额：" + strPaidPrice);
            statusText.setText(mustSpanText("支付状态：", "已付款", R.color.green));
            backePaidPrice.setText(mustSpanText("可退金额：", "￥" + refundablePrice, R.color.green));
            if (mQuiryDetailBean.getRefundablePrice() == 0) {
                importPice.setText("0");
                importPice.setTextColor(getResource().getColor(R.color.light_gray));
                importPice.setEnabled(false);
            }

        }

        /*查询优付卡*/
        if (!CheckUtils.isEmpty(mQuerypayData)) {
            QueryPaBean item = mQuerypayData.get(0);
            if (mQuerypayData.size() > 1) {
                QueryPaBean item1 = mQuerypayData.get(1);
                payMethodText1.setText(item1.getPayMethodText() + ":" + CheckUtils.isEmptyNumber(item1.getAmount()));
            }
            payMethodText.setText(item.getPayMethodText() + ":" + CheckUtils.isEmptyNumber(item.getAmount()));

            for (QueryPaBean queryPaBean : mQuerypayData) {/*余额*/
                if (queryPaBean.getPayMethod() == 3) {
                    refundBalance = queryPaBean.getRefundableAmount();
                    isBalance = true;

                }
                if (queryPaBean.getPayMethod() == 11) {/*优付卡*/
                    refundUpay = queryPaBean.getRefundableAmount();
                    isUpay = true;
                    if (!CheckUtils.isEmpty(queryPaBean.getExtraJson())) {
                        try {
                            JSONObject mJSONObject = new JSONObject(queryPaBean.getExtraJson());
                            payRatio = mJSONObject.getInt("payRatio");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }


                }

            }


        }




    }


    private void calculateClotingCount(List<QuiryDetailBean.ProductListBean> mproductList) {
        int clothingCount = 0;
        int selectClothingCount = 0;
        for (QuiryDetailBean.ProductListBean productListBean : mproductList) {

            if (productListBean.getType() == 1) {
                clothingCount = clothingCount + 1;
            }

            if (productListBean.isCheck() && productListBean.getType() == 1) {/*衣物*/
                selectClothingCount = selectClothingCount + 1;
            }

        }
        String strSelecthite = "";
        if (selectClothingCount != 0 && !isOrderRefund) {
            strSelecthite = ",已选中" + selectClothingCount + "件衣物";
        }
        selectClothingHite.setText("该订单共" + clothingCount + "件衣物" + strSelecthite);


    }

    protected CharSequence mustSpanText(String hite, String colorHite, @ColorRes int id) {
        CharSequence mCharSequence = new SpanUtils().append(hite).append(colorHite).setForegroundColor(getColors(id)).create();
        return mCharSequence;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick({R.id.close_btn, R.id.cancel, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.close_btn:
                dismiss();
                break;
            case R.id.cancel:
                dismiss();
                break;
            case R.id.submit:

                String importpice = getText(importPice);
                String strbackeCause = getText(backeCause);

                if (importpice.isEmpty()) {
                    T.show("请输入退款金额");
                    return;
                } else if (strbackeCause.isEmpty()) {
                    T.show("请输入退款原因");
                    return;
                }else  if (radiogroup.getVisibility()==View.VISIBLE&&radiogroup.getCheckedRadioButtonId()<0&&mRefundMethodBean.size()!=0){
                    T.show("请选择退款方式");

                    return;
            }

                if (mOnDialogSureClickListener != null) {
                    HashMap mHashMap = new HashMap();
                    mHashMap.put(ARG_PARAM1, importpice);
                    mHashMap.put(ARG_PARAM2, strbackeCause);
                    if (radiogroup.getVisibility()==View.VISIBLE&&mRefundMethodBean.size()!=0){
                     String  backMethod  =mRefundMethodBean.get(radiogroup.getCheckedRadioButtonId()).getVal();
                        mHashMap.put(ARG_PARAM3,backMethod);
                    }else{
                        mHashMap.put(ARG_PARAM3,"");
                    }
                    mOnDialogSureClickListener.onSureItemClick(mHashMap);

                }
                dismiss();
                break;
        }
    }
}
